package io.zhifei.modules.sys.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.zhifei.common.exception.RRException;
import io.zhifei.common.utils.ExcelUtil;
import io.zhifei.common.utils.PageUtils;
import io.zhifei.common.utils.R;
import io.zhifei.common.utils.ToolUtils;
import io.zhifei.modules.sys.system.dao.member.MemberDao;
import io.zhifei.modules.sys.system.entity.member.MemberEntity;
import io.zhifei.modules.sys.system.form.CourseRecordParam;
import io.zhifei.modules.sys.system.form.CourseRecordResult;
import io.zhifei.modules.sys.system.form.UserCourseParam;
import io.zhifei.modules.sys.system.form.UserVideoRecordParam;
import io.zhifei.modules.sys.system.form.member.MemberFileResult;
import io.zhifei.modules.sys.system.form.member.MemberParam;
import io.zhifei.modules.sys.system.form.member.MemberResult;
import io.zhifei.modules.sys.system.service.MemberClassService;
import io.zhifei.modules.sys.system.service.member.MemberService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 学员信息 服务实现类
 * </p>
 *
 * @author duke
 * @since 2020-10-10
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Override
    public PageUtils getCourseRecordPageList(Page page, CourseRecordParam param) {
        IPage courseRecordPageList = this.baseMapper.getCourseRecordPageList(page,param);
        return new PageUtils(courseRecordPageList);
    }

    @Override
    public List<CourseRecordResult> getCourseRecordList(CourseRecordParam param) {
        return this.baseMapper.getCourseRecordList(param);
    }

    @Override
    public R updateCourseRecordNumber(CourseRecordParam param) {
        //当减少次数的时候，验证减少次数是否超过剩余次数
        if (2 == param.getType()){
            CourseRecordResult recordResult = this.baseMapper.getCourseRecordDetail(param);
            //减少的次数不能大于总数/大于剩余次数
            if (param.getTotalNumber() > recordResult.getTotalNumber() || param.getTotalNumber() > recordResult.getNumber()){
                return R.error(500,"减少的次数不能大于总数/大于剩余次数");
            }
        }
        this.baseMapper.updateCourseRecordNumber(param);
        return R.ok();
    }

    @Override
    public void updateMember(MemberParam param) {
        MemberResult memberResult = this.baseMapper.getMemberDetail(param);
        if (null != memberResult && !memberResult.getId().equals(param.getId())){
            throw new RRException("学员手机号不能重复");
        }
        MemberEntity oldEntity = getOldEntity(param);
        MemberEntity entity = getEntity(param);
        ToolUtils.copyProperties(entity,oldEntity);
        this.baseMapper.updateById(entity);
    }

    @Override
    public PageUtils getMemberPageList(Page page, MemberParam param) {
        IPage<MemberResult> memberPageList = this.baseMapper.getMemberPageList(page,param);
        return new PageUtils(memberPageList);
    }

    @Override
    public List<MemberResult> getMemberList(MemberParam param) {
        return this.baseMapper.getMemberList(param);
    }

    @Override
    public MemberResult getMemberDetail(MemberParam param) {
        return this.baseMapper.getMemberDetail(param);
    }

    @Override
    public R importMemberExcel(MultipartFile file) {
        XSSFWorkbook wb = null;
        XSSFSheet sheet;
        XSSFRow row;
        //错误信息
        String msg = "";
        //题目结果集
        List<MemberParam> memberParams = new ArrayList<>();

        try {
            InputStream is = file.getInputStream();
            wb = new XSSFWorkbook(is);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //A难度
        sheet = wb.getSheetAt(0);
        // 得到总行数
        int rowNum = sheet.getLastRowNum();

        // 正文内容应该从第二行开始,第一行为表头的标题
        for (int i = 4; i <= rowNum; i++) {
            row = sheet.getRow(i);
            if (null == row){
                break;
            }

            MemberParam memberParam = new MemberParam();
            //备考年份
            String prepareYear = ExcelUtil.getCellFormatValue(
                    row.getCell((short) 0));
            memberParam.setPrepareYear(prepareYear);

            //添加题目到题目结果集中
            memberParams.add(memberParam);

        }
        if (StrUtil.isNotEmpty(msg)){
            return R.error(msg);
        }else {
            return R.ok();
        }
    }

    @Override
    public PageUtils getUserVideoRecordPageList(Page page, String userId) {
         IPage pageList = this.baseMapper.getUserVideoRecordPageList(page,userId);
         return new PageUtils(pageList);
    }

    @Override
    public void addUserVideoRecord(UserVideoRecordParam param) {
        this.baseMapper.addUserVideoRecord(param);
    }

    @Override
    public void addUserCourse(UserCourseParam param) {
         this.baseMapper.addUserCourse(param);
    }

    @Override
    public void addVideoRecord(CourseRecordParam param) {
        this.baseMapper.addVideoRecord(param);
    }

    @Override
    public List<Map<String, Object>> getSingleUserCourse(Long userId) {
        return this.baseMapper.getSingleUserCourse(userId);
    }

    @Override
    public void deleteBatchUserCourse(String[] ids) {
        this.baseMapper.deleteBatchUserCourse(ids);
    }

    @Override
    public void deleteUserCourseByUserId(Long userId,Long classId,Long courseId) {
        this.baseMapper.deleteUserCourseByUserId(userId,classId,courseId);
    }

    @Override
    public PageUtils getMemberFilePageList(Page page, MemberParam param) {
        IPage<MemberFileResult> pageList = this.baseMapper.getMemberFilePageList(page,param);
        List<MemberFileResult> memberResults = pageList.getRecords();
        pageList.setRecords(getScore(memberResults));
        return new PageUtils(pageList);
    }

    @Override
    public List<MemberFileResult> getMemberFileList(MemberParam param) {
        List<MemberFileResult> memberResults = this.baseMapper.getMemberFileList(param);
        return getScore(memberResults);
    }

    /**
     * 转化对象
     * @param param 参数
     * @return
     */
    private MemberEntity getEntity(MemberParam param){
        MemberEntity entity = new MemberEntity();
        ToolUtils.copyProperties(param,entity);
        return entity;
    }

    /**
     * 获取旧的数据
     * @param param
     * @return
     */
    private MemberEntity getOldEntity(MemberParam param) {
        return this.getById(param.getId());
    }

    /**
     * 获取联考总分、综合成绩、英语成绩
     * @param memberFileResults 学员档案信息列表
     * @return
     */
    private List<MemberFileResult> getScore(List<MemberFileResult> memberFileResults){
        memberFileResults.stream().forEach(memberResult -> {
            if (!"0".equals(memberResult.getLkcj())){
                String[] lkcjStr = memberResult.getLkcj().split("/");
                for (int i = 1; i <= lkcjStr.length; i++) {
                    switch (i){
                        case 1:
                            //联考总分
                            memberResult.setEntranceExaminationScore(lkcjStr[i-1]);
                            break;
                        case 2:
                            //综合成绩
                            memberResult.setComprehensiveScore(lkcjStr[i-1]);
                            break;
                        case 3:
                            //英语成绩
                            memberResult.setEnglishScore(lkcjStr[i-1]);
                            break;
                        default:
                            break;
                    }

                }
            }
        });
        return memberFileResults;
    }



}
